package iv1201.model;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.hibernate.tool.hbm2x.StringUtils;

/**
 *
 * @author Mustafa
 */

@Stateless

public class EntityDAO
{
    
    @PersistenceContext(unitName = "iv1201PU")
    private EntityManager em;
    
    public EntityDAO()
    {
    }
   
    /**
     * Login function with basic error handling: Requires a correct
     * username, password & has to have the right permission (only recruiters
     * can log in).
     */
   public String loginRecruiter(String username, String password) 
    {
        // Java Persistence Query Language
        final String queryString = ("SELECT p FROM Person p WHERE p.username=:username AND p.password=:password AND p.role_id=2");

        Query query = em.createQuery(queryString);
        // set in parameters for SQL query
        query.setParameter("username", StringUtils.lowerCase(username));
        query.setParameter("password", StringUtils.lowerCase(password));
        // return query result as a list
        List<Person> result = query.getResultList();
        
        /*
         * If afield is missing, the system returns the same
         * form with an appropriate error message.
         * Returns a string which redirects a user to a specific webpage
         * depending on the type of login error
         */
        if (username.equals("") && password.equals(""))
        {
            return "user_pw";
        }
        
        else if (username.equals(""))
        {
            return "user";
        }
        
        else if (password.equals(""))
        {
            return "pw";
        }

        /*
         * If the system can not authenticate the recruiter, it
         * returns a blank form and tells that the login failed.
         */
        if (result.size() != 1)
        {
            return "wrong";
        }

        return "";
    }

    /*
     * Function for showing the name at the welcaome page once a recruiter
     * has logged in
     */
    public String welcomeLogin(String username)
    {
        final String queryString = ("Select p from Person p where p.username=:username");
        Query query = em.createQuery(queryString);
        
        query.setParameter("username", StringUtils.lowerCase(username));
        List<Person> result = query.getResultList();
        
        Person person = result.get(0);  
        
        return person.getName().toString();        
    }
    
    /*
     * Error handler to make sure that no fields are empty
     * when starting a new application. In order to continue, the fields must
     * be filled.
     */
    public String applicantInfo(String name, String surname, String email) 
    {    
        if (name.equals("") || surname.equals("") || email.equals(""))
        {
            return "wrong";
        }

        return "";
    }
}
